<template>
  <div class="home">
    <div class="content">
      <div class="header">
        <el-page-header content="编辑页面" @back="goBack"></el-page-header>
      </div>
      <div class="selectMoudle">
        <div>
          <span class="text">模块</span>
          <el-radio-group v-model="radio1" fill="#1d2f70">
            <el-radio-button
              v-for="(item, index) in radio"
              :label="item.label"
              :key="index"
            ></el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button class="sendBtn" @click="send">
            发布
            <i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </div>
      </div>
      <div class="inputBox">
        <input
          type="text"
          placeholder="输入标题"
          v-model="editorData.resourcename"
        />
      </div>
      <div class="inputBox">
        <el-upload
          class="upload-demo"
          action="https://jifen.zhportinfo.com/api/v1/resorcefj"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :multiple="false"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="editorData.fileList"
          :http-request="upload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">附件上传</div>
        </el-upload>
      </div>
      <div class="selectZiyuan">
        <span class="resourceTitle">资源模块</span>
        <el-select
          v-model="editorData.classify"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.title"
            :value="item.index"
          ></el-option>
        </el-select>
      </div>
      <div class="editor">
        <textEditor
          @EditorChange="editorChange"
          @uploadImageChange="uploadImageChange"
          :oldcontent="editorData.content"
          :oldremoveIds="editorData.deleImgId"
        ></textEditor>
      </div>
    </div>
  </div>
</template>

<script>
// import axios from "axios";
import textEditor from "@/components/quillEditor";
import {
  get_resourceOnlineDraft,
  put_resourceOnlineDraft,
  delete_resourceOnlineDraft,
} from "@/api/resourceOnlineDraft";
import { put_resource } from "@/api/resorcefj";
import { post_delectImg, post_enclosure } from "@/api/deleteTheInterface";
import { textReplace } from "@/common/textReplace";
import { uploadResorcefj } from "@/api/resorcefj";
import { get_resourcelabel } from "@/api/resourcelabel";
export default {
  name: "Editor",
  data() {
    return {
      editorData: {
        articleId: "", //文章id
        resourcename: "", //资源共享标题
        content: "", //富文本内容
        userid: "", //用户id
        fileList: [],
        classify: "", //资源类型
        deleImgId: [], //需要删除的图片
      },
      timer: null,
      radio1: "资源共享",
      radio: [
        {
          name: "资源共享",
          label: "资源共享",
        },
      ],
      options: [],
    };
  },
  components: {
    textEditor,
  },
  async created() {
    let resourcelabelData = await get_resourcelabel();
    this.options = resourcelabelData.data;
    console.log("this.options", this.options);

    console.log(this.$route.query._id);
    if (!this.$route.query._id) {
      this.$router.push({
        path: "/home",
      });
      return;
    }
    let editData = await get_resourceOnlineDraft({
      query: { _id: this.$route.query._id },
    });
    console.log("editData", editData.data[0]);
    this.editorData = editData.data[0];
    this.$message({
      showClose: true,
      message: "已自动保存成功至草稿箱",
      type: "success",
    });
    clearInterval(this.timer);
    this.timer = null;
    this.setTimer();
  },
  destroyed: function () {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    setTimer() {
      let time = 1000 * 30;
      if (this.timer == null) {
        this.timer = setInterval(async () => {
          console.log("setTimer保存");
          await put_resourceOnlineDraft({
            query: { _id: this.editorData._id },
            update: {
              $set: this.editorData,
            },
          });
          this.$message({
            showClose: true,
            message: "自动保存成功",
            type: "success",
          });
        }, time);
      }
    },
    async uploadImageChange() {
      console.log("uploadImageChange保存");
      await put_resourceOnlineDraft({
        query: { _id: this.editorData._id },
        update: {
          $set: this.editorData,
        },
      });
      this.$message({
        showClose: true,
        message: "自动保存成功",
        type: "success",
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    editorChange(data) {
      this.editorData.content = data.html;
      // console.log("改变前", this.editorData.deleImgId);
      if (this.editorData.deleImgId.length != data.removeIds.length) {
        this.uploadImageChange();
      }
      this.editorData.deleImgId = data.removeIds;
      // this.editorData.textReplace = textReplace(data.html);
      // console.log("改变后", this.editorData.deleImgId);
    },
    async send() {
      if (this.editorData.articleId == "") {
        return this.$alert("请完善文章标题", "提示", {
          confirmButtonText: "确定",
          callback: () => {},
        });
      }
      if (this.editorData.content == "") {
        return this.$alert("请完善文章内容", "提示", {
          confirmButtonText: "确定",
          callback: () => {},
        });
      }
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        let deleArr = this.editorData.deleImgId;
        console.log(deleArr);
        let replaceText = textReplace(this.editorData.content);
        if (this.editorData.fileList.length == 0) {
          this.editorData.fileList = [
            {
              name: "",
              url: "",
              filesName: "",
            },
          ];
        }
        await put_resource({
          query: { _id: this.editorData.articleId },
          update: {
            $set: {
              audit: false,
              resourcename: this.editorData.resourcename, //资源共享标题
              content: this.editorData.content, //富文本内容
              textReplace: replaceText, //文章缩略
              enclosure: this.editorData.fileList[0].url, //附件
              lookenclosure: this.editorData.fileList[0].name, //附件显示名
              filesName: this.editorData.fileList[0].filesName, //资源文件名
              classify: this.editorData.classify,
              release_time: new Date(),
            },
          },
        });
        let dele = await delete_resourceOnlineDraft({
          query: {
            _id: this.editorData._id,
          },
        });
        console.log("dele", dele);

        if (deleArr.length != 0) {
          await post_delectImg({
            deleImgArr: deleArr,
          });
        }
        if (this.editorData.fileDelectArr.length != 0) {
          await post_enclosure({
            deleArr: this.editorData.fileDelectArr,
          });
        }
        setTimeout(() => {
          loading.close();
          this.$message({
            showClose: true,
            message: "发布成功",
            type: "success",
          });
          this.$alert("文章已发布", "提示", {
            confirmButtonText: "确定",
            callback: () => {},
          });
          this.$router.go(-1);
          // this.$router.replace({
          //   path: "/resourceSharing"
          // });
        }, 1000);
      } catch (error) {
        loading.close();
        this.$message.error("错误：" + error);
      }
    },
    //上传文件
    //文件列表移除文件时的钩子
    handleRemove(file) {
      this.editorData.fileDelectArr.push(file.filesName);
      let index = this.editorData.fileList.some((item, index) => {
        if (item.filesName == file.filesName) {
          return index;
        }
      });
      this.editorData.fileList.splice(index, 1);
      this.uploadImageChange();
      console.log(
        "handleRemove",
        this.editorData.fileDelectArr,
        this.editorData.fileList
      );
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    //删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    upload(fileObj) {
      console.log(fileObj.file.name);
      var fileName = fileObj.file.name;
      var index1 = fileName.lastIndexOf(".");
      var index2 = fileName.length;
      let lic = fileName.substring(index1 + 1, index2);
      console.log(lic);

      var formData = new FormData();
      formData.append("lication", lic);
      formData.append("file", fileObj.file);

      uploadResorcefj(formData)
        .then((response) => {
          console.log(response);
          this.editorData.fileList.push(response);
          console.log("总列表", this.editorData.fileList);
          this.uploadImageChange();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  background: #fff;
}
.content {
  width: 100%;
  .header {
    margin: 0 auto;
    width: 1200px;
    margin-top: 20px;
  }
  .selectMoudle {
    margin: 0 auto;
    width: 1200px;
    margin-top: 40px;
    display: flex;
    justify-content: space-between;
    .text {
      font-size: 20px;
      font-weight: 700;
      color: #757575;
      margin-right: 20px;
    }
    .sendBtn {
      background: #1d2f70;
      border: #1d2f70;
      color: #fff;
      &:hover {
        background: rgb(53, 89, 180);
      }
    }
  }
  .selectZiyuan {
    margin: 0 auto;
    width: 1200px;
    margin-top: 30px;
    .resourceTitle {
      font-size: 20px;
      color: #6c6c6c;
      font-weight: 600;
      margin-right: 20px;
    }
  }
  .inputBox {
    margin: 0 auto;
    width: 1200px;
    margin-top: 30px;
    input {
      outline-style: none;
      outline-style: none;
      border: 0px;
      border-bottom: 2px solid #ccc;
      width: 1200px;
      padding: 13px 14px;
      font-size: 28px;
      font-weight: 700;
      font-family: "Microsoft soft";
      box-sizing: border-box;
    }
  }
  // margin-top: -19px;
  padding: 20px;
  box-sizing: border-box;
  .editor {
    min-height: 500px;
    margin-top: 40px;
  }
}
</style>
